/**
 * 
 */
package com.baihui.taobao.quartz.triggers;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

import com.baihui.taobao.db.DBConnectionMgr;
import com.baihui.taobao.quartz.constant.JobConstant;
import com.baihui.taobao.quartz.jobs.BuyerImportJob;
import com.baihui.taobao.quartz.jobs.InvImportJob;
import com.baihui.taobao.quartz.jobs.OrderImportJob;
import com.baihui.taobao.quartz.jobs.ProductImportJob;

/**
 * @author dev
 * 
 */
public class BaiHuiImportTriggle {
	SchedulerFactory schedulerFactory = new StdSchedulerFactory();
	
	/**
	 * 根據用戶執行對應的任務
	 * @param userID
	 * @param jobClass
	 * @param schedulerExp
	 * @throws SchedulerException
	 */
	public void startTask(String userID, Class jobClass, String schedulerExp)
			throws SchedulerException {	
		Scheduler scheduler = schedulerFactory.getScheduler();

		long ctime = System.currentTimeMillis();

		JobDetail jobDetail = new JobDetail("jobDetail", "jobDetailGroup",
				jobClass);
		CronTrigger cronTrigger = new CronTrigger("cronTrigger",
				"triggerGroup");
		try {
			CronExpression cexp = new CronExpression(schedulerExp);
			cronTrigger.setCronExpression(cexp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		scheduler.scheduleJob(jobDetail, cronTrigger);
		scheduler.start();
	}

	/**
	 * 開始調度
	 */
	public void scheduler() {
		//獲取所有關聯用戶記錄
        Connection cn = null;
        PreparedStatement ps=null;
        try {
            cn = DBConnectionMgr.getConnection();
            cn.setAutoCommit(false);
            //取得目前导入交易的最大时间，将哪个时间作为开始时间
            String sql = "select ts.user_id,tt.* from topsession ts,ttriggle tt where ts.user_id=tt.userid";
            ps=cn.prepareStatement(sql);
            ResultSet rs=ps.executeQuery();
            while(rs.next()) {
            	String userID=String.valueOf(rs.getLong("user_id"));
            	int jobType=rs.getInt("jobid");
            	String triggleExp=rs.getString("cronExp");
            	
            	Class jobClass=null;
            	switch(jobType) {
            	case 1:
            		jobClass=ProductImportJob.class;
            		break;
            	case 2:
            		jobClass=OrderImportJob.class;
            		break;
            	case 3:
            		jobClass=BuyerImportJob.class;
            		break;
            	case 4:
            		jobClass=InvImportJob.class;
            	}
            	
            	//開始執行任務
            	startTask(userID,jobClass,triggleExp);
            }
            
        }
        catch(Exception exception){
        	exception.printStackTrace();
        }
	}
}
